package com.cms.entity;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.alibaba.fastjson.annotation.JSONField;
import com.cms.entity.base.BaseMember;
import com.cms.util.DBUtils;
import com.cms.util.WeixinUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

/**
 * Entity -会员
 * 
 * 
 * 
 */
@SuppressWarnings("serial")
public class Member extends BaseMember<Member> {
	
    /** 树路径分隔符 */
    public static final String TREE_PATH_SEPARATOR = ",";
    
    /**
     * 会员session名称
     */
    public static final String SESSION_MEMBER="session_member";
    
    /**
     * 账户类型
     */
    public enum AccountType{
    	ALIPAY("支付宝"),
    	WEIXIN("微信");
    	public String text;
    	AccountType(String text){
			this.text = text;
		}
		public String getText(){
			return this.text;
		} 
    }
    
    /**
     * 上级会员
     */
    private Member parent;
    
    
    /**
     * 获取上级会员
     * @return  上级会员
     */
    public Member getParent(){
        if(parent == null){
            parent = findById(getParentId());
        }
        return parent;
    }
    
    /**
     * 会员等级
     */
    @JSONField(serialize=false)  
    private MemberRank memberRank;

    /**
     * 获取会员等级
     * 
     * @return 会员等级 
     */
    public MemberRank getMemberRank(){
        if(memberRank == null && getMemberRankId()!=null){
        	memberRank =  new MemberRank().dao().findById(getMemberRankId());
        }
        return memberRank;
    }
    
    /**
     * 获取所有上级地区ID
     * 
     * @return 所有上级地区ID
     */
    public Long[] getParentIds() {
        String[] treePaths = StringUtils.split(getTreePath(), TREE_PATH_SEPARATOR);
        Long[] result = new Long[treePaths.length];
        for (int i = 0; i < treePaths.length; i++) {
            result[i] = Long.valueOf(treePaths[i]);
        }
        return result;
    }
    
    
   /**
     * 查找会员分页
     * 
     * @return 会员分页
     */
    public Page<Member> findPage(String mobile,String nickname,Integer pageNumber,Integer pageSize){
        String filterSql = "";
        if(StringUtils.isNotBlank(mobile)){
            filterSql+= " and mobile like '%"+mobile+"%'";
        }
        if(StringUtils.isNotBlank(nickname)){
            filterSql+= " and nickname like '%"+nickname+"%'";
        }
        String orderBySql = DBUtils.getOrderBySql("createDate desc");
        return paginate(pageNumber, pageSize, "select *", "from cms_member where 1=1 "+filterSql+orderBySql);
    }
    
    /**
     * 根据用户名查找会员
     * 
     * @param mobile
     *          用户名
     * @return  会员
     */
    public Member findByMobile(String mobile){
        return findFirst("select * from cms_member where mobile=? ", mobile);
    }
    
    /**
     * 根据weixinOpenId查找会员
     * 
     * @param weixinOpenId
     *          用户名
     * @return  会员
     */
    public Member findByWeixinOpenId(String weixinOpenId){
        return findFirst("select * from cms_member where weixinOpenId=? ", weixinOpenId);
    }
    
    /**
     * 根据qqOpenId查找会员
     * 
     * @param qqOpenId
     *          用户名
     * @return  会员
     */
    public Member findByQqOpenId(String qqOpenId){
        return findFirst("select * from cms_member where qqOpenId=? ", qqOpenId);
    }
    
    /**
     * 根据用户名查找会员
     * 
     * @return  会员
     */
    public Member findByCode(String code){
        return findFirst("select * from cms_member where code=? ", code);
    }
    
    /**
     * 查找code
     * 
     * @return code
     */
    public String findCode(){
        String code;
        while(true){
            code = RandomStringUtils.randomNumeric(6);
            if(findByCode(code)==null){
                break;
            }
        }
        return code;
    }
    
    /**
     * 设置值
     * 
     */
    public void setValue() {
        if (getParentId() != null) {
            String treePath = getParent().getTreePath();
            String [] treePaths = treePath.split(TREE_PATH_SEPARATOR);
            if(treePaths.length==4){
                treePath = TREE_PATH_SEPARATOR+treePaths[2]+TREE_PATH_SEPARATOR+treePaths[3]+TREE_PATH_SEPARATOR;
            }
            setTreePath(treePath + getParent().getId() + TREE_PATH_SEPARATOR);
        } else {
            setTreePath(TREE_PATH_SEPARATOR);
        }
    }
    
    /**
     * 查找当日注册人数
     * @return
     */
    public Integer findTodayRegisterCount(Long memberId){
    	String startDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd")+" 00:00:00";
    	String endDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd")+" 23:59:59";
    	String sql="select count(*) from cms_member where createDate >='"+startDate+"' and createDate <='"+endDate+"' and treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%' ";
    	return Db.queryInt(sql);
    }
    
    /**
     * 查找当日报单人数
     * @return
     */
    public Integer findTodayPaymentCount(Long memberId){
    	String startDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd")+" 00:00:00";
    	String endDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd")+" 23:59:59";
    	String sql="select count(*) from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%' and id in(select memberId from cms_payment where createDate >='"+startDate+"' and createDate <='"+endDate+"') group by id ";
    	return Db.queryInt(sql);
    }
    
    /**
     * 查找已注册未报单人数
     * @return
     */
    public Integer findNotPaymentCount(Long memberId){
    	String sql="select count(*) from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%' and id not in(select memberId from cms_payment) group by id ";
    	return Db.queryInt(sql);
    }
    
    /**
     * 查找会员
     */
    public List<Member> findLevelList(Long memberId,Integer grade){
        String sql="";
        if(grade == null){
        	sql+="select * from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%'";
        }else{
        	switch (grade) {
        	case 1:
        		sql+="select * from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"'";
        		break;
        	case 2:
        		sql+="select * from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%"+TREE_PATH_SEPARATOR+"'";
        		break;
        	case 3:
        		sql+="select * from cms_member where treePath like '"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%"+TREE_PATH_SEPARATOR+"%"+TREE_PATH_SEPARATOR+"'";
        		break;
        	}
        }
        return find(sql);
    }
    
    public Integer findTodayFansCount(Long memberId){
    	String tody = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
    	String startTime = tody+" 00:00:00";
    	String endTime = tody+" 23:59:59";
        return Db.queryInt("select count(*) from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%' and createDate>='"+startTime+"' and createDate <='"+endTime+"'");
    }
    
    public Integer findMonthFansCount(Long memberId){
    	String tody = DateFormatUtils.format(new Date(), "yyyy-MM");
    	String startTime = tody+"-01 00:00:00";
    	String endTime = tody+"-31 23:59:59";
        return Db.queryInt("select count(*) from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%' and createDate>='"+startTime+"' and createDate <='"+endTime+"'");
    }
    
    public Integer findFansCount(Long memberId){
    	return Db.queryInt("select count(*) from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%'");
    }
    
    public List<Member> findFans(Long memberId){
    	return find("select * from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%'");
    }
    
    public Page<Member> findFansPage(Integer pageNumber,Integer pageSize,Long memberId){
    	return paginate(pageNumber, pageSize, "select * "," from cms_member where treePath like '%"+TREE_PATH_SEPARATOR+memberId+TREE_PATH_SEPARATOR+"%'");
    }
    
    /**
     * 保存微信会员
     * 
     * @return 微信会员
     */
    public Member saveWeixinMember(String openId,Long parentId){
        //获取用户信息
        Map<String,Object> userInfo = WeixinUtils.getUserInfo(openId);
        Member member = new Member();
        member.setCreateDate(new Date());
        member.setModifyDate(new Date());
        member.setCode(findCode());
        member.setParentId(parentId);
        member.setNickname((String)userInfo.get("nickname"));
        member.setAvatar((String)userInfo.get("headimgurl"));
        member.setWeixinOpenId(openId);
        member.setValue();
        member.save();
        return member;
    }
}
